package org.deltaset.meta.internal;

import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.deltaset.meta.Catalog;
import org.deltaset.meta.MetaField;

/**
 *
 * @author dmakariev
 */
class CatalogImpl implements Catalog {

    private static final Logger logger = Logger.getLogger(CatalogImpl.class.getName());

    CatalogImpl(Map<String, String> templateMap, String unsuportedTemplateSrc, String metaType) {
        this.templateMap = templateMap;
        this.unsuportedTemplateSrc = unsuportedTemplateSrc;
        this.metaType = metaType;
    }
    private final Map<String, String> templateMap;
    private final String unsuportedTemplateSrc;
    private final String metaType;

    @Override
    public String templateSrc(final String modifier, final MetaField metaField) {
        final String genericKey = prepareKey(modifier, metaField);
        final String metaTypeKey = genericKey + "." + metaType;
        if (templateMap.containsKey(metaTypeKey)) {
            final String template = templateMap.get(metaTypeKey);
            logger.log(Level.FINE, "modifier={0};CatalogKey={1};templateSrc={2};metaField={3}", new Object[]{modifier, metaTypeKey, template, metaField.toString()});
            return template;
        } else if (templateMap.containsKey(genericKey)) {
            final String template = templateMap.get(genericKey);
            logger.log(Level.FINE, "modifier={0};CatalogKey={1};templateSrc={2};metaField={3}", new Object[]{modifier, genericKey, template, metaField.toString()});
            return template;
        } else {
            logger.log(Level.WARNING, "modifier={0};CatalogKey(UNSUPPORTED)={1};templateSrc={1};metaField={2}", new Object[]{modifier, genericKey, unsuportedTemplateSrc, metaField.toString()});
            return unsuportedTemplateSrc;
        }
    }

    private static String prepareKey(final String modifier, final MetaField metaField) {
        final boolean isCustomType = "custom".equals(metaField.getPropertyType());
        final String propertyType = (true == isCustomType) ? metaField.getOriginalType().getName() : metaField.getPropertyType();
        final String key = propertyType + "." + modifier;
        return key;
    }
}
